<div class="chart-editor">
    <div class="row">
        <div class="span4">
            <div class="sidebar">
                {#if activeColumn} {#if customColumn}

                <ComputedColumnEditor
                    on:updateTable="refs.hot.update()"
                    on:renderTable="refs.hot.render()"
                    on:unselect="set({activeColumn:false})"
                    bind:column="customColumn"
                    bind:columns
                />

                <button on:click="force(event, true)" class="btn">
                    {__('describe / edit-format')}
                </button>

                {:elseif columnFormat}

                <CustomColumnFormat on:updateTable="refs.hot.update()" on:renderTable="refs.hot.render()" bind:column="columnFormat" bind:columns />

                {#if columnFormat.isComputed}
                <button class="btn" on:click="force(event, false)"><i class="fa  fa-chevron-left"></i> {__('describe / edit-formula')}</button>
                {/if} {/if} {#if activeColumn.type() == 'number'}
                <Histogram bind:values="activeValues" bind:format="activeFormat" />
                {/if} {:elseif multiSelection}

                <h3 class="first">{__('describe / show-hide-multi')}</h3>

                <ul class="unstyled">
                    <li style="margin-bottom: 5px">
                        <button class="btn" on:click="hideMultiple(multiSelection, false)">
                            <i class="fa fa-eye"></i> {__('describe / show-selected')}
                        </button>
                    </li>
                    <li>
                        <button class="btn" on:click="hideMultiple(multiSelection, true)">
                            <i class="fa fa-eye-slash"></i> {__('describe / hide-selected')}
                        </button>
                    </li>
                </ul>

                {:else}

                <h3 class="first">{ __(`Make sure the data looks right`) }</h3>

                <p>{@html __(`describe / data-looks-right`) }</p>

                <Checkbox label="{ __("First row as label") }" bind:value="firstRowIsHeader" />

                <h4>{__(`describe / locale-select / hed`)}</h4>

                <p>{@html __(`describe / locale-select / body`)}</p>

                <select bind:value="locale">
                    {#each locales as locale}
                    <option value="{locale.value}">{locale.label} ({locale.value})</option>
                    {/each}
                </select>

                {/if}

                <hr />

                <div class="btn-group">
                    <a class="btn submit" href="upload"><i class="icon-chevron-left"></i> {__('Back')}</a>
                    <a href="visualize" class="submit btn btn-primary" id="describe-proceed">
                        {__('Proceed')} <i class="icon-chevron-right icon-white"></i
                    ></a>
                </div>
            </div>
        </div>
        <div class="span8">
            <div class="help">{@html __('describe / info-table-header')} <img src="/static/img/arrow.svg" /></div>
            <div class="pull-right" style="margin-bottom: 10px">
                <div class="sort-box">
                    <div class="btn-group" ref:sortDropdownGroup>
                        <button class="btn dropdown-toggle" data-toggle="dropdown">
                            {@html __('describe / sort-by')}… <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu sort-menu">
                            <li class="{'-'==sortBy?'active':''}">
                                <a on:click="sort(event, '-')" href="#s">{@html __('describe / no-sorting')}</a>
                            </li>
                            {#each columns as col}
                            <li class="{col.name()==sortBy?'active':''}">
                                <a on:click="sort(event, col.name(), true)" href="#/{col.name()}">
                                    <i
                                        on:click="sort(event, col.name(), true)"
                                        class="fa fa-sort-{col.type()=='text'?'alpha':'amount'}-asc fa-fw"
                                    ></i>
                                    <i
                                        on:click="sort(event, col.name(), false)"
                                        class="fa fa-sort-{col.type()=='text'?'alpha':'amount'}-desc fa-fw"
                                    ></i
                                    >&nbsp;&nbsp;&nbsp;{col.title()}</a
                                >
                            </li>
                            {/each}
                        </ul>
                    </div>
                </div>

                <div class="search-box form-search">
                    <i class="im im-magnifier"></i>
                    <div class="{searchResults.length > 0 ? 'input-append' : ''}">
                        <input
                            autocomplete="screw-you-google-chrome"
                            type="search"
                            on:keypress="keyPress(event)"
                            placeholder="{__('Search data table')}"
                            bind:value="search"
                            ref:search
                            class="{searchResults.length > 0?'with-results':''} search-query"
                        />
                        {#if searchResults.length > 0}
                        <div class="btn-group">
                            <button class="btn" on:click="nextResult(-1)">
                                <i class="fa fa-chevron-up"></i>
                            </button>
                            <button class="btn" on:click="nextResult(+1)">
                                <i class="fa fa-chevron-down"></i>
                            </button>
                        </div>
                        {/if}
                    </div>

                    {#if search}
                    <div class="results">
                        {#if searchResults.length > 0} {searchIndexSafe+1} {__(`describe / search / of`) } {searchResults.length} {__(`describe /
                        search / results`) } {:elseif search} { __(`describe / search / no-matches`) } {/if}
                    </div>
                    {/if}
                </div>
            </div>

            <Handsontable
                ref:hot
                bind:data="chartData"
                bind:transpose
                bind:firstRowIsHeader
                bind:fixedColumnsLeft
                bind:activeColumn
                bind:readonly
                bind:sorting
                bind:search
                bind:searchResults
                bind:searchIndex
                bind:multiSelection
                on:resetSort="set({sortBy:'-'})"
            />

            <div class="buttons below-table pull-right">
                <button class="btn transpose" on:click="toggleTranspose()">
                    <img src="/static/css/chart-editor/transpose.png" /> {__(`describe / transpose-long`)}
                </button>

                <button on:click="addComputedColumn()" class="btn computed-columns">
                    <i class="fa fa-calculator"></i> {__(`computed columns / add-btn`)}…
                </button>

                <button on:click="revertChanges()" class="btn {has_changes?'':'disabled'}" id="reset-data-changes">
                    <i class="fa fa-undo"></i> {__(`Revert changes`)}…
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    /* global chart */
    import ComputedColumnEditor from './ComputedColumnEditor.html';
    import CustomColumnFormat from './CustomColumnFormat.html';
    import Histogram from './Histogram.html';
    import Handsontable from '../controls/hot/Handsontable.html';
    import Checkbox from '../controls/Checkbox.html';

    import { __ } from '../shared/l10n';
    import { arrayToObject } from '../shared/utils.js';
    import clone from '../shared/clone.js';

    export default {
        components: { Handsontable, Checkbox, ComputedColumnEditor, CustomColumnFormat, Histogram },
        data() {
            return {
                locale: 'en-US',
                search: '',
                chartData: '',
                readonly: false,
                transpose: false,
                firstRowIsHeader: true,
                fixedColumnsLeft: 0,
                searchIndex: 0,
                activeColumn: false,
                customColumn: false,
                columnFormat: false,
                multiSelection: false,
                forceColumnFormat: false,
                searchResults: [],
                sortBy: '-',
                sortDir: true
            };
        },
        computed: {
            searchIndexSafe({ searchIndex, searchResults }) {
                if (searchIndex < 0) searchIndex += searchResults.length;
                searchIndex = searchIndex % searchResults.length;
                return searchIndex;
            },
            customColumn({ activeColumn, forceColumnFormat }) {
                return activeColumn && !forceColumnFormat && activeColumn.isComputed ? activeColumn : false;
            },
            columnFormat({ activeColumn, forceColumnFormat }) {
                return activeColumn && (!activeColumn.isComputed || forceColumnFormat) ? activeColumn : false;
            },
            activeValues({ activeColumn }) {
                return activeColumn ? activeColumn.values() : [];
            },
            activeFormat({ activeColumn, $dw_chart }) {
                return activeColumn ? $dw_chart.columnFormatter(activeColumn) : d => d;
            },
            columns({ activeColumn }) {
                const ds = chart.dataset();
                if (!activeColumn) return ds ? ds.columns() : [];
                try {
                    return ds.columns().filter(col => !col.isComputed);
                } catch (e) {
                    return [];
                }
            },
            sorting({ sortBy, sortDir }) {
                return { sortBy, sortDir };
            }
        },
        helpers: { __ },
        methods: {
            nextResult(diff) {
                let { searchIndex, searchResults } = this.get();
                searchIndex += diff;
                if (searchIndex < 0) searchIndex += searchResults.length;
                searchIndex = searchIndex % searchResults.length;
                this.set({ searchIndex });
            },
            keyPress(event) {
                if (event.key === 'F3' || event.key === 'Enter') {
                    this.nextResult(event.shiftKey ? -1 : 1);
                }
            },
            toggleTranspose() {
                this.set({ activeColumn: false });
                this.set({ transpose: !this.get().transpose });
                setTimeout(() => this.refs.hot.update(), 500);
                // ;
            },
            revertChanges() {
                const chart = this.store.get().dw_chart;
                chart.set('metadata.data.changes', []);
                chart.saveSoon();
                this.refs.hot.update();
            },
            cmFocus() {
                setTimeout(() => {
                    this.refs.hot.get().hot.render();
                }, 100);
            },
            addComputedColumn() {
                const chart = this.store.get().dw_chart;
                const ds = chart.dataset();
                const computed = arrayToObject(chart.get('metadata.describe.computed-columns', {}));
                // find new id
                let i = 1;
                while (ds.hasColumn(`Column ${i}`)) {
                    i++;
                }
                const id = `Column ${i}`;
                computed[id] = '';
                chart.set('metadata.describe.computed-columns', computed);
                chart.saveSoon();
                const ds2 = chart.dataset(true);
                this.refs.hot.update();
                this.set({ activeColumn: ds2.column(id) });
            },
            sort(event, col, ascending) {
                event.preventDefault();
                event.stopPropagation();
                this.set({ sortBy: col, sortDir: ascending });
                // hide the dropdown menu
                this.refs.sortDropdownGroup.classList.remove('open');
            },
            force(event, val = true) {
                event.preventDefault();
                this.set({ forceColumnFormat: val });
            },
            hideMultiple(columns, hide) {
                const chart = this.store.get().dw_chart;
                const colFmt = clone(chart.get('metadata.data.column-format', {}));
                columns.forEach(col => {
                    if (colFmt[col.name()]) colFmt[col.name()].ignore = hide;
                    else {
                        colFmt[col.name()] = { type: 'auto', ignore: hide };
                    }
                });
                chart.set('metadata.data.column-format', colFmt);
                chart.saveSoon();
                setTimeout(() => {
                    this.refs.hot.get().hot.render();
                }, 10);
                this.set({ multiSelection: false });
            }
        },
        oncreate() {
            window.addEventListener('keypress', event => {
                if (event.ctrlKey && event.key === 'f') {
                    event.preventDefault();
                    if (this.refs.search !== window.document.activeElement) {
                        this.refs.search.focus();
                    } else {
                        this.nextResult(+1);
                    }
                }
            });
        },
        // eslint-disable-next-line
        onupdate({ changed, current }) {
            if (changed.activeColumn && !current.activeColumn) {
                this.set({ forceColumnFormat: false });
            }
            const sync = {
                transpose: 'metadata.data.transpose',
                firstRowIsHeader: 'metadata.data.horizontal-header',
                locale: 'language'
            };
            Object.keys(sync).forEach(svelteKey => {
                if (changed[svelteKey]) {
                    const svelteValue = current[svelteKey];
                    const metadataKey = sync[svelteKey];
                    this.store.get().dw_chart.set(`${metadataKey}`, svelteValue);
                    if (svelteKey === 'locale') {
                        if (!svelteValue) return;
                        this.store.get().dw_chart.locale(svelteValue, () => {
                            this.refs.hot.render();
                        });
                    }
                }
            });
        }
    };
</script>

<style lang="less">
    .help {
        display: inline-block;
        font-style: italic;
        line-height: 0px;
        color: #aaa;
    }

    .below-table {
        margin-top: 20px;
    }
    .span8 {
        padding-top: 1em;
    }
    .btn.transpose img {
        width: 12px;
        vertical-align: baseline;
    }
    .sort-box {
        display: inline-block;
        vertical-align: top;
        margin-right: 1ex;
        .sort-menu li a .fa {
            opacity: 0.5;
            &:hover {
                opacity: 1;
            }
        }

        .dropdown-menu > li > a {
            padding: 3px 20px 3px 10px;
        }
    }
    .search-box {
        display: inline-block;
        vertical-align: top;
        position: relative;
        .results {
            color: gray;
            display: inline-block;
            vertical-align: text-bottom;
            margin-left: 1ex;
            margin-right: 1ex;
        }
        input {
            padding-left: 26px;
            width: 24ex;
            border-radius: 15px;
            &.with-results {
                width: 18ex;
                border-bottom-right-radius: 0px;
                border-top-right-radius: 0px;
            }
        }
        .im-magnifier {
            position: absolute;
            left: 8px;
            top: 9px;
            color: #bbb;
            font-size: 16px;
            z-index: 4;
        }
        .btn-group .btn {
            padding-left: 6px;
            padding-right: 6px;
        }
        .btn-group .btn:first-child {
            border-radius: 0;
        }
        .btn-group .btn:last-child {
            border-bottom-right-radius: 15px;
            border-top-right-radius: 15px;
            padding-right: 9px;
        }
    }
    :global(html .form-horizontal .control-group) {
        margin-bottom: 10px;
    }
    :global(.vis-option-type-checkbox) {
        label {
            display: inline-block;
            width: auto !important;
        }
    }

    :global(.sidebar span.type-hl) {
        background-color: white;
        padding: 0 3px;
        font-family: 'Roboto Mono';
        border: 1px solid #cccccc;
    }
</style>
